


import glUtils from "../utils/glUtils";

import {mat4} from "gl-matrix";

/**
 * desc:
 *  点精灵
 */

const vs = `#version 300 es

layout(location = 0) in vec4 vPosition;

uniform mat4 model_matrix;
uniform mat4 proj_matrix;

void main() {
    vec4 pos = proj_matrix * model_matrix * vPosition;
    gl_PointSize = 20.0;
    gl_Position = pos;
}
`;

const fs = `#version 300 es
precision mediump float;

// uniform sampler2D sprite_texture;
out vec4 color;

void main() {
    
    const vec4 color1 = vec4(0.6,0.0,0.0,1.0);
    const vec4 color2 = vec4(0.9,0.7,1.0,0.0);
    
    vec2 temp = gl_PointCoord - vec2(0.5);
    float f = dot(temp,temp);
    if(f > 0.25){
        discard;
        // color = vec4(1.0,1.0,0,1.0); 
    }else{
        color = mix(color1,color2,smoothstep(0.1,0.25,f)); 
    }
      
}`;
const POINT_COUNT = 4;
// const ItemSize = Float32Array.BYTES_PER_ELEMENT;

function randomValue() {
    return (Math.random() * 2 - 1) * 500;
}

export default {

    gl:null,

    //
    proj_matrix: mat4.create(),
    model_matrix: mat4.create(),

    // handle
    vPosition : 0,

    uProjMat:0,
    uModelMat:0,

    init(gl){
        this.gl = gl;

        this.program = glUtils.createProgram(gl,vs,fs);
        gl.useProgram(this.program);
        this.uProjMat = gl.getUniformLocation(this.program,'proj_matrix');
        this.uModelMat = gl.getUniformLocation(this.program,'model_matrix');

        let vertexPositions = [];
        for(let i = 0; i < POINT_COUNT; ++i){
            vertexPositions.push(randomValue(),randomValue());
        }

        this.vao = gl.createVertexArray();
        gl.bindVertexArray(this.vao);

        this.vbo = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,this.vbo);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertexPositions),gl.STATIC_DRAW);

        gl.enableVertexAttribArray(this.vPosition);
        gl.vertexAttribPointer(this.vPosition,2,gl.FLOAT,false,0,0);

        gl.bindVertexArray(null);

        mat4.perspective(this.proj_matrix,60,4/3,0.1,2000);
        mat4.fromTranslation(this.model_matrix,[0,0,-100.0]);
    },

    render(){
        let gl = this.gl;

        gl.useProgram(this.program);
        gl.uniformMatrix4fv(this.uProjMat,false,this.proj_matrix);
        gl.uniformMatrix4fv(this.uModelMat,false,this.model_matrix);

        gl.bindVertexArray(this.vao);
        gl.drawArrays(gl.POINTS,0,4);
        gl.bindVertexArray(null);
    },

}